package com.dragon.graduation.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dragon.graduation.user.entity.UserEntity;
import com.dragon.graduation.user.mapper.UserMapper;
import com.dragon.graduation.user.service.UserService;
import com.dragon.graduation.userRole.entity.UserRoleEntity;
import com.dragon.graduation.userRole.mapper.UserRoleMapper;
import com.dragon.md5.Md5Encrypt;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author dragon
 * @since 2025-02-28 21:23:44
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    private final UserRoleMapper userRoleMapper;
    @Override
    public Integer addUser(String userId, String name, Integer role) {
        UserEntity entity = UserEntity.builder()
                .userName(userId)
                .realName(name)
                .password("123456")
                .role(role)
                .build();
        entity.setPassword(Md5Encrypt.encryptPassword(entity.getUserName(), entity.getPassword()));
        save(entity);
        UserRoleEntity build = UserRoleEntity.builder()
                .roleId(role)
                .userId(entity.getId())
                .build();
        userRoleMapper.insert(build);
        return entity.getId();
    }

    @Override
    public void removeByUserIds(List<Integer> idList) {
        List<UserEntity> list = baseMapper.selectBatchIds(idList);
        if (!CollectionUtils.isEmpty(list)) {
            List<Integer> userIdList = list.stream().map(UserEntity::getId).collect(Collectors.toList());
            userRoleMapper.deleteByUserList(userIdList);
            baseMapper.deleteBatchIds(idList);
        }
    }
}
